package client;

import java.util.HashMap;


public abstract class ClientNavigator {

	private Client client;
	
	private NavigatorContext context = new NavigatorContext(this);


	public void start() {		
		String command = "";
		while((command = getClient().getCommand()) != null) {
			getClient().doCommand(command);
		}
	}

	public Client getClient() {
		return client;
	}

	public void addCommand(Command command) {
		context.commandChoices.put(command.getName(), command);
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public void clearCommands() {
		context.commandChoices.clear();
	}

	public Command getCommand(final String url) {
		for(final String commandName : context.commandChoices.keySet()) {
			//System.out.println( "checking if " + url + " starts with " + commandName );
			if(url != null && commandName != null && url.startsWith(commandName)) {
				final Command command = context.commandChoices.get(commandName);
				String arguments = url.replaceFirst(commandName, "");
				command.context = context;
				command.arguments = arguments.trim();
				command.resetParameters();
				int i = 0;
				for(String parameter : arguments.split(" ")) {						
					if(parameter.equals(""))
						continue;
					if(command.getRequiredParameterNames().length > i) {
						//System.out.println("required parameter " + command.getRequiredParameterNames()[i] + " " + parameter);
						command.setParameter(command.getRequiredParameterNames()[i], parameter);
					}
					else if(command.getRequiredParameterNames().length > 0) {
						String name = command.getRequiredParameterNames()[command.getRequiredParameterNames().length-1];
						Object value = command.getParameter(command.getRequiredParameterNames()[command.getRequiredParameterNames().length-1]);
						//System.out.println("2 command.setParameter(" + name + " to " + value);
						command.setParameter(name, value + " " + parameter);
					}
					i++;
				}
				for(String parameterName : command.getRequiredParameterNames())
					if(command.getParameter(parameterName) == null)
						return new Command("usage") {
							@Override
							protected void doFunction() {
								String params = "";
								for(String parameterName : command.getRequiredParameterNames())
									params += " <" + parameterName + ">";
								ret("error", "Usage: " + commandName + params);
							}
						};
				//System.out.println("Get Command: " + commandName + command.getParameters());
				return command;
					
			}
		}
		return new Command("command not found") {
			@Override
			protected void doFunction() {
				ret("error", "command not found: " + url);
			}
		};
	}
	
	public HashMap<String, Command> getCommandMap() {
		return context.commandChoices;
	}
	
}
